package com.util.xls;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.Objects;

/**
 * @auther carter
 * create time    2018-06-11
 */
public final class EmailUtils {

    private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class);


    public static boolean sendMail(String toAddress, String fromTitle, String mailSubject, String mailBody){
        return sendMail(toAddress,fromTitle,mailSubject,mailBody,null);
    }
    /**
     *
     * @param toAddress		收件人邮箱
     * @param mailSubject	    邮件主题
     * @param mailBody		    邮件正文
     * @param fromTitle        来源标题
     * @param  ccArray         抄送列表
     * @return
     */
    public static boolean sendMail(String toAddress, String fromTitle, String mailSubject, String mailBody,String[] ccArray){

        String username = "erpnotify@stosz.com";
        String password = "bugu123";

        logger.info("发送邮件【{}】,主題:【{}】",toAddress,mailSubject);
        try {
            HtmlEmail email = new HtmlEmail();


            email.setHostName("smtp.qiye.163.com");
            email.setSmtpPort(25);
            email.setAuthenticator(new DefaultAuthenticator(username, password));
            email.setCharset(Charset.forName("UTF-8").name());
            email.setFrom(username, fromTitle);
            email.addTo(toAddress);
            if (Objects.nonNull(ccArray) && ccArray.length>0){
                email.addCc(ccArray);
            }
            email.setSubject(mailSubject);
            email.setMsg(mailBody);

            email.send();
            return true;
        } catch (EmailException e) {
            logger.error("发送邮件出错:"+e.getMessage(), e);

        }
        return false;
    }

}
